﻿#ifndef GLWIDGET_H
#define GLWIDGET_H

#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QVector3D>
#include <QTimer>
#include <QMouseEvent>
#include "texture_shader_program.h"
#include "geometry/table.h"
#include "table_drawer.h"
#include "color_shader_program.h"
#include "geometry/mallet.h"
#include "mallet_drawer.h"
#include "shader_program.h"
#include "geometry/puck.h"
#include "geometry/geometry.h"
#include "puck_drawer.h"
#include "constant.h"
#include "geometry/geometry.h"

// 眼睛距离目原地(0,0,0)的距离
static const float eyeDistance = 2.2f;

class GLWidget : public QOpenGLWidget, protected QOpenGLFunctions {
    public:
        explicit GLWidget(QWidget *parent = nullptr);
        ~GLWidget();

    protected:
        void initializeGL() override;
        void resizeGL(int w, int h) override;
        void paintGL() override;
        void mousePressEvent(QMouseEvent *event) override;
        void mouseMoveEvent (QMouseEvent *event) override;
        void mouseReleaseEvent (QMouseEvent *event) override;

    private slots:
        void animate();

    private:
        void positionTableInScene();
        void positionObjectInScene(float x, float y, float z);
        void positionObjectInScene(QVector3D &pos);
        void calcEyePosition();
        void normalized2D2Ray(Ray &ray, float x, float y);
        void blueMalletPuckCollideCheck(); 

    private:
        // 矩阵
        QMatrix4x4 m_viewMatrix;
        QMatrix4x4 m_projMatrix;
        QMatrix4x4 m_viewProjectMatrix;
        QMatrix4x4 m_invertedViewProjectMatrix;
        QMatrix4x4 m_modelViewProjectMatrix;
        // shader,geometry
        TextureShaderProgram *m_textureProgram = nullptr;
        Table *m_table = nullptr;
        TableDrawer *m_tableDrawer = nullptr;
        Mallet *m_mallet = nullptr;
        MalletDrawer *m_malletDrawer = nullptr;
        SimpleShaderProgram *m_simpleProgram = nullptr;
        Puck *m_puck = nullptr;
        PuckDrawer *m_puckDrawer = nullptr;
        // 动画定时器
        QTimer *m_timer = nullptr;
        QVector3D m_eyePosition{0.f, 1.2f, eyeDistance};
        // 动画xz平面上对x轴的角度
        float m_theda = 0.f;
        // 拖放
        bool m_blueMalletDraging = false;
        QVector3D m_blueMalletPrePosition;
        QVector3D m_blueMalletPosition{0.f, MALLET_HEIGHT / 2.f, 0.4f};
        QVector3D m_redMalletPosition{0.f, MALLET_HEIGHT / 2.f, -0.4f};
        // 击打冰球
        QVector3D m_puckPosition{0.f, 0.f, 0.f};
        // 冰球运动的方向矢量
        QVector3D m_puckVector{0.f, 0.f, 0.f};
        // 碰撞标记
        bool m_blueMalletCollided = false;
};

#endif // GLWIDGET_H
